package com.zide.file.controller;

import cn.hutool.core.util.StrUtil;
import com.zide.common.config.XianYingConfig;
import com.zide.common.constant.Constants;
import com.zide.common.core.domain.CommonResult;
import com.zide.common.utils.StringUtils;
import com.zide.common.utils.file.FileUploadUtils;
import com.zide.common.utils.file.FileUtils;
import com.zide.framework.config.ServerConfig;
import com.zide.file.config.LocalFileConfig;
import com.zide.file.domain.vo.result.FileUploadResultVO;
import com.zide.file.service.IImageFileService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 石添
 * @date 2024/4/29 15:33
 */
@Tag(name = "本地图片管理")
@RestController
@RequestMapping("/li")
@Slf4j
public class LocalImageController {

    @Resource
    private ServerConfig serverConfig;

    @Resource
    private IImageFileService imageFileService;

    private static final String FILE_DELIMETER = ",";

    @Operation(summary = "上传头像")
    @PostMapping("/avatar")
    public CommonResult uploadAvatar(@RequestParam("file") MultipartFile file) {
        FileUploadResultVO result = imageFileService.uploadAvatar(file);
        return CommonResult.success(result);
    }

    @Operation(summary = "本地单图片上传")
    @PostMapping("/s_upload")
    public CommonResult uploadFile(@RequestParam("file") MultipartFile file, @RequestParam("imgType") String imgType) {
        try {
            // 上传文件路径
            String filePath = LocalFileConfig.getUploadImgPath();
            if(StrUtil.isNotEmpty(imgType)) {
                filePath = filePath + imgType;
            }
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = LocalFileConfig.getImgPath() + imgType + "/" + fileName;
            FileUploadResultVO fileResultVO = new FileUploadResultVO();
            fileResultVO.setUrl(url);
            fileResultVO.setFilename(FileUtils.getName(fileName));
            return CommonResult.success(fileResultVO);
        } catch (Exception e) {
            return CommonResult.error(e.getMessage());
        }
    }

    @Operation(summary = "本地多文件上传")
    @PostMapping("/uploads")
    public CommonResult uploadFiles(List<MultipartFile> files) {
        try {
            // 上传文件路径
            String filePath = XianYingConfig.getUploadPath();
            List<String> urls = new ArrayList<String>();
            List<String> fileNames = new ArrayList<String>();
            List<String> newFileNames = new ArrayList<String>();
            List<String> originalFilenames = new ArrayList<String>();
            for (MultipartFile file : files) {
                // 上传并返回新文件名称
                String fileName = FileUploadUtils.upload(filePath, file);
                String url = serverConfig.getUrl() + fileName;
                urls.add(url);
                fileNames.add(fileName);
                newFileNames.add(FileUtils.getName(fileName));
                originalFilenames.add(file.getOriginalFilename());
            }
            CommonResult ajax = CommonResult.success();
            ajax.put("urls", StringUtils.join(urls, FILE_DELIMETER));
            ajax.put("fileNames", StringUtils.join(fileNames, FILE_DELIMETER));
            ajax.put("newFileNames", StringUtils.join(newFileNames, FILE_DELIMETER));
            ajax.put("originalFilenames", StringUtils.join(originalFilenames, FILE_DELIMETER));
            return ajax;
        } catch (Exception e) {
            return CommonResult.error(e.getMessage());
        }
    }

    @Operation(summary = "本地资源通用下载")
    @GetMapping("/download/resource")
    public void resourceDownload(String resource, HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        try {
            if (!FileUtils.checkAllowDownload(resource)) {
                throw new Exception(StringUtils.format("资源文件({})非法，不允许下载。 ", resource));
            }
            // 本地资源路径
            String localPath = XianYingConfig.getProfile();
            // 数据库资源地址
            String downloadPath = localPath + StringUtils.substringAfter(resource, Constants.RESOURCE_PREFIX);
            // 下载名称
            String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, downloadName);
            FileUtils.writeBytes(downloadPath, response.getOutputStream());
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }
    @Operation(summary = "本地通用下载请求")
    @GetMapping("/download")
    public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request) {
        try {
            if (!FileUtils.checkAllowDownload(fileName)) {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = XianYingConfig.getDownloadPath() + fileName;

            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, realFileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete) {
                FileUtils.deleteFile(filePath);
            }
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }

}
